package com.deepblue.image.maker.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * freemaker工具类
 *
 * @author yymagicer
 * @version 1.0
 * @date 2021/11/8 下午5:30
 */
@Component
public class FreemakerUtil {


    @Resource
    private  Configuration configuration;


   public  Template getTemplate(String ftlPath){
       try {
           return configuration.getTemplate(ftlPath);
       } catch (IOException e) {
           e.printStackTrace();
       }
       return null;
   }

   public  void write(String ftlPath,String writeFilePath,Object data) throws IOException {
       Template template = getTemplate(ftlPath);
       if(null!=template){
           try (Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(writeFilePath), StandardCharsets.UTF_8.name()), 10240)){
               template.process(data, out);
           } catch (FileNotFoundException | UnsupportedEncodingException | TemplateException e) {
               e.printStackTrace();
           }
       }
   }
}
